/**
 * 
 */
package com.sqq.model.kl;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.ext.plugin.tablebind.TableBind;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sqq.jfinalbase.SqqModel;
import com.sqq.util.DateUtil;

/**
 *@author gqy
 *完成所有对表kl_macvisit的操作
 *2015-1-20
 */
@TableBind(tableName = "kl_macvisit")
public class KlMacVisitModel extends SqqModel<KlMacVisitModel>{

	public static KlMacVisitModel dao = new KlMacVisitModel();
	
	/**
	 * 根据探针扫描到的mac信息和时间技术客户到场信息
	 * 统计原则：
	 * 	1.在店持续逗留2分钟以上（包括2分钟）统计为有效到场，否则统计为无效到场
	 * 	2.同一个mac两个时间间隔大于180分钟表示两次会话即两次到场
	 */
	public static void klMacVisit(){		
		String timeTag = KlParameterModel.getKlMacVisitLastDatetime();//该时间是最后一次计算是的时间点，会持久化到数据库或配置文件中，避免重复统计已经统计过的数据  //TODO:以后完善
		List<Record> find = RouterMacScanModel.list(timeTag);
        String mac=null;
        Date createTime=null;
        long id = 0;
        String gwMac=null;
        
        Date lastCreateTime=null;
        long lastId = 0;
        
        for(Record record:find){
        	if(mac==null){//第一次执行
        		lastCreateTime = record.getDate("create_time");
        		lastId = record.getInt("id");
        		mac = record.getStr("mac");
        		createTime = lastCreateTime;
        		id = lastId;
        		gwMac= record.getStr("gw_mac");
        	}
        	else{
        		String tmpMac = record.getStr("mac");
        		Date tmpTime = record.getDate("create_time");
        		long tmpId = record.getInt("id");
        		String tmpGwmac = record.getStr("gw_mac");
        		if(tmpGwmac.equals(gwMac)){//同一个商家
        			if(tmpMac.equals(mac)){
            			long intervalMin = DateUtil.intervalTime(createTime,tmpTime);
            			if(intervalMin < 180){
            		        lastCreateTime=tmpTime;
            		        lastId = tmpId;
            				continue;
            			}
            			else{
            				insertKlMacVisit(mac, createTime, lastCreateTime, gwMac);
            				/*Map<String,Object> map =new HashMap<String, Object>();
            				map.put("mac", mac);
            				map.put("start_time", createTime);
            				map.put("end_time", lastCreateTime);
            				map.put("gw_mac", gwMac);
            				long min = DateUtil.intervalTime(createTime,lastCreateTime);
            				map.put("lasttime", min);
            				if(min>=2){
            					map.put("usefull", "1");
            				}
            				else{
            					map.put("usefull", "0");
            				}
            				new KlMacVisitModel().setAttrs(map).save();*/
            		        lastCreateTime=tmpTime;
            		        lastId = tmpId; 
            				mac = tmpMac;
                    		createTime = tmpTime;
                    		id = tmpId;
            			}
            		}
            		else{
            			if(lastId == id ){
            				insertKlMacVisit(mac, createTime, createTime, gwMac);
            				/*Map<String,Object> map =new HashMap<String, Object>();
            				map.put("mac", mac);
            				map.put("start_time", createTime);
            				map.put("end_time", createTime);
            				map.put("lasttime", 0);
            				map.put("usefull", "0");
            				map.put("gw_mac", gwMac);
            				new KlMacVisitModel().setAttrs(map).save();*/
            			}
            			else{
            				insertKlMacVisit(mac, createTime, lastCreateTime, gwMac);
            				/*Map<String,Object> map =new HashMap<String, Object>();
            				map.put("mac", mac);
            				map.put("start_time", createTime);
            				map.put("end_time", lastCreateTime);
            				map.put("gw_mac", gwMac);
            				long min = DateUtil.intervalTime(createTime,lastCreateTime);
            				map.put("lasttime", min);
            				if(min>=2){
            					map.put("usefull", "1");
            				}
            				else{
            					map.put("usefull", "0");
            				}
            				map.put("lasttime", min);
            				new KlMacVisitModel().setAttrs(map).save();*/
            			}
        		        lastCreateTime=tmpTime;
        		        lastId = tmpId;
        				mac = tmpMac;
                		createTime = tmpTime;
                		id = tmpId;
                		gwMac = tmpGwmac;
            		}
        		}
        		else{
        			if(lastId == id ){
        				insertKlMacVisit(mac, createTime, createTime, gwMac);
        				/*Map<String,Object> map =new HashMap<String, Object>();
        				map.put("mac", mac);
        				map.put("start_time", createTime);
        				map.put("end_time", createTime);
        				map.put("lasttime", 0);
        				map.put("usefull", "0");
        				map.put("gw_mac", gwMac);
        				new KlMacVisitModel().setAttrs(map).save();*/
        			}
        			else{
        				insertKlMacVisit(mac, createTime, lastCreateTime, gwMac);
        			}
    		        lastCreateTime=tmpTime;
    		        lastId = tmpId;
    				mac = tmpMac;
            		createTime = tmpTime;
            		id = tmpId;
            		gwMac = tmpGwmac;
        		}
        	}
        }
        KlParameterModel.storeKlMacVisitLastDatetime(lastCreateTime);
    }
	
	/**
	 * 插入客流访问统计表
	 * @param mac
	 * @param createTime
	 * @param lastCreateTime
	 * @param gwMac
	 */
	private static void insertKlMacVisit(String mac,Date createTime,Date lastCreateTime,String gwMac){
		Map<String,Object> map =new HashMap<String, Object>();
		map.put("mac", mac);
		map.put("start_time", createTime);
		map.put("end_time", lastCreateTime);
		map.put("gw_mac", gwMac);
		long min = DateUtil.intervalTime(createTime,lastCreateTime);
		map.put("lasttime", min);
		if(min>=2){//根据到场时间是否超过2分钟确认是否有效到场
			map.put("usefull", "1");
		}
		else{
			map.put("usefull", "0");
		}
		map.put("lasttime", min);
		new KlMacVisitModel().setAttrs(map).save();
	}
	
	/**
	 * 根据时间段统计某个探针设备探测到到mac数据量
	 * @param bTime    统计开始时间  格式  YYYY-MM-DD HH:MI:SS
	 * @param eTime    统计结束时间  格式  YYYY-MM-DD HH:MI:SS
	 * @param staTime  统计时间段  格式  YYYYMMDDHHMI
	 * @return
	 */
	public static List<Record> findMacStaByDatetime(String bTime,String eTime,String staTime){
		String sql ="SELECT sum(distinct mac) visittimes ,gw_mac,'"+staTime+"' sta_time " +
				"from kl_macvisit where " +
				"(( ? >= start_time and ? <=end_time) or (? >= start_time and ? <=end_time)) "+
				"and usefull='1' group by gw_mac ";
		List<Record> list = Db.find(sql, bTime,bTime,eTime,eTime);
		return list;
	}

	/**
	 * 根据最后一次统计时间获取客户访问信息
	 * @param presentTime
	 * @return
	 */
	public static List<Record> findMacinfo(String presentTime){
		String sql = "select gw_mac,mac,start_time from kl_macvisit " +
				"where start_time>= ? and usefull='1' group by gw_mac,mac order by start_time ";
		List<Record> list = Db.find(sql,presentTime);
		return list;
	}
	
	/**
	 * 根据mac和gwMac统计到店次数
	 * @param mac
	 * @param gwMac
	 * @return
	 */
	public static int findMacVisitTimes(String mac,String gwMac){
		String sql = "select count(id) times from kl_macvisit where mac=? and gw_mac=?";
		Record record = Db.findFirst(sql, mac,gwMac);
		if(record==null){
			return 0;
		}
		else{
			int times = record.getInt("times");
			return times;
		}
	}
	
	/**
	 * 判定mac是否是商家的粉丝客户
	 * @param mac
	 * @param gwMac
	 * @param timeTag
	 * @return
	 */
	public static boolean isFansMac(String mac,String gwMac,String timeTag){
		Date date = DateUtil.stringToDate(timeTag);
		Date date_15 = DateUtil.add(date, Calendar.DAY_OF_MONTH, -15);
		String dateStr = DateUtil.format(date_15);
		String sql= "select count(id) times from kl_macvisit where usefull = '1' and mac = ? and gwMac =? and start_time>= ? and start_time<= ?";
		Record record = Db.findFirst(sql,mac,gwMac,dateStr,timeTag);
		if(record==null){
			return false;
		}
		else{
			int times = record.getInt("times");
			return times>=2;
		}
		
	}
}
